package com.inctech.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	HttpSession session = request.getSession();
    	Object currentUser = session.getAttribute("currentUser");
    	
    	// path == "/ERP-System"
        String path = request.getContextPath();
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
            AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
            //没有声明需要权限,或者声明不验证权限
            if(authPassport == null || authPassport.validate() == false)
            	return true;
            else if(currentUser != null && currentUser.toString() != "")
            	return true;
            else//如果验证失败
            {
                //返回到登录界面
                response.sendRedirect(path + "/account/login.do");
                return false;
            }       
        }
        else
            return true;   
     }
}